//
//  TravelNotesViewController.m
//  MapEXPO
//
//  Created by 洪雯 on 16/4/2.
//  Copyright © 2016年 洪雯. All rights reserved.
//

#import "TravelNotesViewController.h"
#import <AFNetworking.h>
#import "listModel.h"
#import "UIImageView+WebCache.h"
#import "TacticCollectionViewCell.h"
#import "TacticCollectionReusableView.h"

#define SCREEN_WIDTH ([UIScreen  mainScreen].bounds.size.width)
#define SCREEN_HEIGHT ([UIScreen mainScreen].bounds.size.height)

@interface TravelNotesViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property NSMutableArray * arrayData;
@property UICollectionView * collectionView;
@property NSArray *textArray;
@property NSMutableArray * imageArray;
@end

@implementation TravelNotesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self GETRequest];
    [self createCollectionView];
}
#pragma mark 请求数据
- (void)GETRequest
{
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    //因为我们要获取text/plain类型数据,防止报错
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // Get请求
    [manager GET:@"http://192.168.199.211:8000/strategy/" parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前的数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求成功，解析数据
       // NSLog(@"%@", responseObject);
        _arrayData = [[NSMutableArray alloc]init];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray * listArr = [dic objectForKey:@"list"];
        for (NSDictionary * listDic in listArr) {
            listModel * model = [[listModel alloc]init];
            model.strategyContent = [listDic objectForKey:@"strategyContent"];
            model.strategySummary = [listDic objectForKey:@"strategySummary"];
            model.strategyTitle = [listDic objectForKey:@"strategyTitle"];
            model.strategyImages= [listDic objectForKey:@"strategyImages"];
            [_arrayData addObject:model];
        }
        for (listModel * model in _arrayData) {
            NSLog(@"内容 : %@",model.strategyContent);
        }
        
        
        //NSLog(@"%@", dic);
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        NSLog(@"%@", [error localizedDescription]);
    }];
}

#pragma mark 创建表格
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    //指定布局方式为垂直
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.minimumLineSpacing = 10;//最小行间距(当垂直布局时是行间距，当水平布局时可以理解为列间距)
    flow.minimumInteritemSpacing = 10;//两个单元格之间的最小间距
    
    //创建CollectionView并指定布局对象
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flow];
    //    _collectionView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:239/255.0f alpha:1.0];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.view addSubview:_collectionView];
    
    //注册用xib定制的cell，各参数的含义同UITableViewCell的注册
    [_collectionView registerNib:[UINib nibWithNibName:@"TacticCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TCellID"];
    
    //注册用xib定制的分组脚
    //参数二：用来区分是分组头还是分组脚
    [_collectionView registerNib:[UINib nibWithNibName:@"TacticCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TSectionID"];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _arrayData.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    listModel * model = [[listModel alloc] init];
    model = [_arrayData objectAtIndex:section];
    NSString * text = model.strategyImages;
    _textArray = [text componentsSeparatedByString:@","];
    _imageArray = [[NSMutableArray alloc] init];
    for (NSString * str in _textArray) {
        NSString * image = [NSString stringWithFormat:@"https://awpublic.oss-cn-beijing.aliyuncs.com/%@",str];
        [_imageArray addObject:image];
    }
    NSLog(@"-----%@",_imageArray[0]);
    //NSArray *arr = [_textArray objectAtIndex:section];
    return _textArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TacticCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TCellID" forIndexPath:indexPath];
    [cell.ImageView.layer setMasksToBounds:YES];
    [cell.ImageView.layer setCornerRadius:5.0];
    [cell.ImageView sd_setImageWithURL:[NSURL URLWithString:self.imageArray[indexPath.row]]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH  - 10, SCREEN_WIDTH /2);
}

//协议中的方法，用于返回整个CollectionView上、左、下、右距四边的间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    //上、左、下、右的边距
    return UIEdgeInsetsMake(0, 5, 0, 5);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    //宽度随便定，系统会自动取collectionView的宽度
    //高度为分组头的高度
    return CGSizeMake(0, 320);
}

//协议中的方法，用来返回CollectionView的分组头或者分组脚
//参数二：用来区分是分组头还是分组脚
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //重用分组头，因为前边注册过，所以重用一定会成功
    //参数一：用来区分是分组头还是分组脚
    //参数二：注册分组头时指定的ID
    TacticCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"TSectionID" forIndexPath:indexPath];
        listModel * model = [[listModel alloc] init];
        model = _arrayData[indexPath.row];
        header.TitleTabel.text = model.strategyTitle;
        header.ContionLabel.text = model.strategyContent;
        header.SummaryLabel.text = model.strategySummary;
    
    return header;
}


//#pragma mark UITableViewDelegate&UITableViewDataSource
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
//    return _arrayData.count;
//}
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    static NSString *cellId = @"cellID";
//    TacticTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellId];
//    if (!cell) {
//        cell = [[[NSBundle mainBundle] loadNibNamed:@"TacticTableViewCell" owner:nil options:nil] lastObject];
//    }
//    listModel * model = [[listModel alloc] init];
//    model = _arrayData[indexPath.row];
//    cell.TitleLabel.text = model.strategyTitle;
//    cell.ContentLabel.text = model.strategyContent;
//    cell.SummaryLabel.text = model.strategySummary;
//    NSString * text = model.strategyImages;
//    // 分割文本到数组
//    _textArray = [text componentsSeparatedByString:@","];
//    //[cell.contentView sd_setImageWithURL:[NSURL URLWithString:self.textArray[indexPath.row]]];
//    return cell;
//}
//
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return 70;
//}



@end
